from django.db import models
from django.contrib.auth.models import User


END_RESULT_DEFAULT_NAME = "Life sucks"
DEFAULT_USER_EMAIL = "reality.tree@gmail.com"

OPEN = 'OPEN'
SOLVED = 'SOLVED'
WILL_NOT_SOLVE = 'WILL_NOT_SOLVE'



class Tag(models.Model):
    """A keyword describing something, e.g., a Problem."""
    name = models.CharField(max_length=100)
    
    def __unicode__(self):
        return unicode(self.name)



class Problem(models.Model):
    """An undesired effect in a person or team's reality.
    A problem can be a root cause, i.e., not derived from
    any other problem, or can be caused by other
    problems."""
    
    STATUS_CHOICES = (
        (OPEN, 'Still open'),
        (SOLVED, 'Solved'),
        (WILL_NOT_SOLVE, 'Will not solve'),        
    )
    
    IMPORTANCE_CHOICES = (
        (1, '1 - Not so important'),
        (2, '2'),
        (3, '3 - Important'),
        (4, '4'),
        (5, '5 - Critical'),
    )

    name = models.CharField(max_length=500)
    person = models.ForeignKey(User)
    description = models.TextField(max_length=4000, null=True, blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES)
    importance = models.IntegerField(choices=IMPORTANCE_CHOICES)
    is_initial_problem = models.BooleanField(default=False)
    tags = models.ManyToManyField(Tag, null=True, blank=True)
    issued = models.DateTimeField(auto_now=True)
    
    def __unicode__(self):
        return unicode(self.name)
    
    def populate_from_map(self, map, user):
        self.name = map["name"]
        self.person = user
        self.description = map["description"]
        self.status = OPEN
        self.importance = map["importance"]
        self.is_initial_problem = False
        
    def set_tags(self, tags_string):
        if tags_string != "":
            tags = []
            for t in tags_string.split(","):
                query = Tag.objects.filter(name=t)
                if query.count() > 0:
                    tag = query[0]
                else:
                    tag = Tag(name=t)
                    tag.save()
                tags.append(tag)
            self.tags = tags


class CausalRelation(models.Model):
    person = models.ForeignKey(User)
    cause = models.ForeignKey(Problem, related_name="cause")
    effect = models.ForeignKey(Problem, related_name="effect")
    issued = models.DateTimeField(auto_now=True)
    
    def __unicode__(self):
        return "causal relation between %s and %s" % (self.cause.name, self.effect.name)
    